#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:烟证有效期限不足
code:SmokeValidation
tableName:
columnName:
groups:准入>烟商
dependencies:BTM
type:常用指标
dataSourceType:在线指标
description:
eof'''

'''
申请企业主申请贷款时烟证有效日期小于贷款到期日期则拒绝
ratingRequest: 接口返回数据
timeLimit	Integer		申请还款期限(单位月)
yancaozhengStartDate	String	是	烟草证有效期限_起始。取值示例:"2015-03-05"
yancaozhengEndDate	String	是	烟草证有效期限_结束。取值示例:"2018-03-05"

"Factor1 = 烟草证有效期限_结束 - （申请日期 + 申请还款期限）；
Factor2 = 烟草证有效期限_结束 - 烟草证有效期限_起始，将Factor2精确转换为年；
IF Factor1 ＜0 or Factor 2 ＞5年 then Factor = 1 else Factor = 0"

'''

import sys
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')


def SmokeValidation():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/',' ']
    loan_duration = ['3', '6', '9', '12', 3, 6, 9, 12]
    try:
        if Formate(ratingRequest['yancaozhengEndDate']) is not None and ratingRequest.get('timeLimit') in loan_duration:
            time_limit = int(ratingRequest['timeLimit'])
            # start_date = datetime.datetime.strptime(Formate(ratingRequest['yancaozhengStartDate']), '%Y-%m-%d')
            end_date = datetime.datetime.strptime(Formate(ratingRequest['yancaozhengEndDate']), '%Y-%m-%d')
            loanEnd_date = (datetime.datetime.now() + pd.tseries.offsets.DateOffset(months=time_limit)).strftime("%Y-%m-%d")
            Factor1 = (end_date - datetime.datetime.strptime(loanEnd_date, "%Y-%m-%d")).days
        else:
            Factor1 = None

        if Formate(ratingRequest['yancaozhengStartDate']) is not None and Formate(ratingRequest['yancaozhengEndDate']) is not None :
            start_date = datetime.datetime.strptime(Formate(ratingRequest['yancaozhengStartDate']), '%Y-%m-%d')
            end_date = datetime.datetime.strptime(Formate(ratingRequest['yancaozhengEndDate']), '%Y-%m-%d')
            r = relativedelta(end_date, start_date)
            Factor2 = r.years + r.months/float(12) + r.days/float(365)
        else:
            Factor2 = None
        #F1 F2 都为None 返回缺失值 , F1>=0 F2<=5 且都不为None 返回0  其他返回1
        if Factor1 is None or Factor2 is None:
            return u'缺失值'
        elif Factor1 >= 0 and Factor2 <= 5:
            return 0
        else:
            return 1
    except:
        return u'缺失值'


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


result = SmokeValidation()